<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Validator;
use App\Model\AdminModel;

class LoginController extends Controller
{
    //
    public function index() {
        return view('admin.login');
    }
    //登录
    public function login(Request $request) {
        // dd($request->input());
        //获取验证码
        $code = trim($request->input('code'));
        $rules = [ 'code' => 'captcha' ];
        $message = ['code.captcha' => '验证码输入不正确'];
        $validator = Validator::make(['code' => $code] , $rules , $message);

        //判断验证码
        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return [
                'msg' => $msg,
                'status' => 'fail'
            ];
        }

        //获取用户名以及密码
        $admin_name = trim($request->input('admin_name'));
        $admin_pass = trim($request->input('admin_pass'));

        //模型验证用户名密码是否正确
        $admin_model = new AdminModel;
        $res = $admin_model->checkLogin($admin_name,$admin_pass);

        //记录用户的登录状态
        session(['username' => $admin_name]);

        return $res;

    }
    //退出登录
    public function logout() {
        //清除用户的登录状态
        session(['username' => null]);
        //重定向
        return redirect('admin/login');
    }

    //检测密码 原始密码实时验证
    public function checkPass(Request $request) {
        //用户名
        $username = session('username');
        //输入的密码
        $password = trim($request->input('param'));

        //模型验证用户名密码是否正确
        $admin_model = new AdminModel;
        $res = $admin_model->checkLogin($username , $password);

        //判断输入密码跟储存的密码
        if ($res['status'] == 'success') {
            //返回key值必须是 info 跟 status validform规定的
            return ['info' => '密码正确 可以修改' , 'status' => 'y'];
        } else {
            return ['info' => '密码不正确' , 'status' => 'n'];
        }
    }
}
